package com.summer.mall.util;

import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

public class FileUploadUtil {

    private static final String product_prefix_url = "localhost:8080/uploads/product_images/";
    private static final String user_prefix_url = "localhost:8080/uploads/user_images/";
    private static final String location_uploads_url = "src/main/resources/uploads";
    private static final String uuid = UUID.randomUUID().toString();



    public static String urlPre() {
        File path = null;
        try {
            path = new File(ResourceUtils.getURL(location_uploads_url).getPath());
            File upload = new File(path.getAbsolutePath(), "/product_images/");
            System.out.println(path);
            if (!upload.exists()) upload.mkdirs();
            return upload.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return "/";
    }

    public static String saveProductImage(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        //获取扩展名jpg
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        //为了避免相同文件名出现被覆盖的情况出现,
        String uploadFileName = uuid +"."+ fileExtensionName;
        //将上传路径前缀改为文件夹下的绝对路径
        String path = urlPre();
        if (file == null) return "";

        File filepath = new File(path, uploadFileName);
        //判断路径是否存在，如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        //将上传文件保存到一个目标文件当中
        try {
            file.transferTo(new File(path + File.separator + uploadFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return product_prefix_url + uploadFileName;
    }

}
